import { contextBridge, ipcRenderer } from "electron";
import { readFileSync } from "fs";
import path from "path";
const querystring = require("querystring");

const listeners = {};
ipcRenderer.on("totalUnreadCount", function (event, ...args) {
  if (listeners["totalUnreadCount"]) {
    listeners["totalUnreadCount"].forEach((listener) => {
      listener(this, ...args);
    });
  }
});

ipcRenderer.on("sendToHost", (event, channel, ...args) => {
  ipcRenderer.sendToHost(channel, ...args);
});

contextBridge.exposeInMainWorld("electron", {
  utils: {
    querystring,
    path,
    readPublicFile: (fileName) => {
      return readFileSync(
        path.resolve(__dirname, process.env.QUASAR_PUBLIC_FOLDER, fileName)
      ).toString();
    },
    preload:
      (process.env.DEV ? "file://" : "") +
      path.resolve(__dirname, process.env.QUASAR_ELECTRON_PRELOAD),
  },
  on: (channel, listener) => {
    if (!listeners[channel]) {
      listeners[channel] = [];
    }
    listeners[channel].push(listener);
  },
  onUpdate: (callback) => {
    console.log("aaaa");
    if (callback && callback instanceof Function) {
      console.log("bbbb");
      ipcRenderer.on("update", (event, data) => {
        console.log("cccc");
        callback(data);
      });
    }
  },
  create: async (name, options) => {
    const id = await ipcRenderer.invoke("createWindow", name, options);
    const xhr = {
      show() {
        return ipcRenderer.invoke("showWindow", id);
      },
    };
    return xhr;
  },
  view: {
    create: async (name, options) => {
      await ipcRenderer.invoke("createView", name, options);
      return true;
    },
  },
  send: (channel, ...args) => {
    ipcRenderer.send(channel, ...args);
    ipcRenderer.sendToHost(channel, ...args);
  },
  getCurrentCookies: (url) => ipcRenderer.invoke("getCurrentCookies", url),
  clientRequest: (options, data, headers) =>
    ipcRenderer.invoke("clientRequest", options, data, headers),
  notify: (title, options) => {
    const xhr = {
      notify: new Notification("options.title", { body: "ffff" }),
      onClick: (callback) => (xhr.notify.onclick = callback),
    };
    return xhr;
  },
});
